<template>
  <view class="pageBg pdb120 box-b">

    <view class="pd262800 box-b">
      <template v-if="orderList && orderList.length > 0">
        <repair-item
          v-for="item in orderList"
          :key="item.orderid"
          :order="item"
          @api_func_cancelOrder="api_func_cancelOrder"
          @recordExpressDelivery="showDrawer"
          @signFor="signFor"
          @toLogistics="toLogistics"
          @toPayment="showDrawer"
        ></repair-item>
      </template>

      <no-data
        v-if="showOrder"
        classStyle="width:213rpx;height:182rpx;margin: 225rpx auto 53rpx;"
        titleColor="#808080"
        nullName="noData.png"
        title="暂无报修记录"
      >
        <template slot="click-title">
          <view class="w340 btn background-theme fs34 white ffmi fw400 login-btn mg50a0 ltsp4 mgt130"
            @click.stop="toPage('/pages/product/repair-report/repair-report-detail',true)">
            我要报修
          </view>
        </template>
      </no-data>
    </view>

    <repair-status
      v-if="!showOrder"
      :btnName="btnName"
      @toOrder="toPage('/pages/product/repair-report/repair-report-detail',true)">
    </repair-status>

    <!--  录入快递  -->
    <tips-popup
      topTitle="快递信息录入"
      topClass="mg48440 pdb38 box-b bdb808 flex-align lh34 fs34 fw600 ffmi color26"
      classNameMask="bg00006"
      :show="showPop['expressDelivery']"
      type="bottom-radio"
      :showThemeDelete="true"
      class="middle-box box-b"
      style="position: relative"
      @hide="closeDrawer('expressDelivery')"
    >

      <view class="box-b mg044">
<!--        <text-item-->
<!--          className="fs26 color26 lh28 mgt44 mgb16"-->
<!--          title="请录入快递信息，以便我们收到包裹第一时间为您服务">-->
<!--        </text-item>-->
<!--        <c-textarea-->
<!--          v-model="order.routercode"-->
<!--          class="h142 pd1820 bdd00 radius12 box-b color1a w100 lh30 fs24 disb"-->
<!--          placeholder-class="fs24 colorb3"-->
<!--          :max="500"-->
<!--          placeholder="请录入快递单号"-->
<!--        ></c-textarea>-->
        <cInput
          bgDefultColor="bdbd00"
          pdClass=""
          v-model="order.routercode"
          :requireRed="true"
          :showClear="true"
          textClass="fs26 color26 lh28 mgt44 mgb16 flex-align"
          :textNameShow="true"
          textName="请录入快递信息，以便我们收到包裹第一时间为您服务"
          placeholder="请录入快递单号"
          class="w100 mgb40"
        >
          <template v-if="$pallet != 'H5'">
            <view class="mgl10" @click="scanRouterCode">
              <server-image
                class="img46 disb"
                name="repair/20241028005.png"
                mode="aspectFill"
              ></server-image>
            </view>
          </template>
        </cInput>
        <view
          class="w570 h90 flex-box background-sub white radius45 fw400 fs34 ffmi ltsp8 mg55a50"
          :class="{ 'bgd2': btnDisabled }"
          @click="!btnDisabled && api_func_submitRouterInfo()"
        >
          保 存
        </view>
      </view>

    </tips-popup>

    <!--  支付维修费用  -->
    <tips-popup
      topTitle="支付维修费用"
      topClass="mg48440 pdb38 box-b bdb808 flex-align lh34 fs34 fw600 ffmi color26"
      classNameMask="bg00006"
      :show="showPop['payment']"
      type="bottom-radio"
      :showThemeDelete="true"
      class="middle-box box-b"
      style="position: relative"
      @hide="closeDrawer('payment')"
    >

      <view
        v-if="order"
        class="box-b mg044">
        <text-item
          className="fs26 color26 lh28 mgt44 mgb16"
          title="本次售后服务待支付费用">
        </text-item>
        <view class="mgt100 flex-box color26 ffpo">
          <view class="fs102">
            {{order.fee || 0}}
          </view>
          <view class="fs36 mgt33 mgl10">
            元
          </view>
        </view>
        <view
          class="w570 h90 flex-box background-sub white radius45 fw400 fs34 ffmi ltsp8 mg95a50"
          :class="{ 'bgd2': !againClick }"
          @click="againClick && api_func_getpayparams()"
        >
          立即支付
        </view>
      </view>

    </tips-popup>

  </view>
</template>

<script>
import repairItem from '@/pages/member/components/repair-item';
import repairStatus from '@/pages/member/components/repair-status';
import tipsPopup from '@/components/tips-popup';
import cTextarea from '@/components/c-textarea';
import { mapState } from 'vuex';
import cInput from '@/components/c-input';
export default {
  components: {
    repairItem,
    repairStatus,
    tipsPopup,
    cTextarea,
    cInput,
  },
  data() {
    return {
      orderList: [],
      current: 1,
      showOrder: false,
      hasNextPage: false,
      againClick: true, //禁止数据频繁切换
      // 报修
      btnName: '我要报修',
      // 弹框
      showPop: {
        expressDelivery: false, // 录快递
        payment: false, // 支付
      },
      order: {}
    };
  },
  computed: {
    ...mapState(['memberInfo']),
    btnDisabled: function () {
      let vm = this;
      return !vm.order.routercode
    },
  },
  onReachBottom() {
    // 列表分页
    // if (this.hasNextPage) {
    //   uni.showToast({
    //     title: '已是最后一页',
    //     icon: 'none',
    //     duration: 1500,
    //   });
    //   return;
    // }
    // this.getList();
  },
  onLoad() {
    this.getList();
  },
  onShow() {
    const vm = this;

    // 报修订单详情改变
    const repairChange = uni.getStorageSync('repairChange');
    if (repairChange) {
      uni.removeStorageSync('repairChange');
      vm.initListDate();
      vm.getList();
    }
  },
  destroyed() {
    const repairChange = uni.getStorageSync('repairChange');
    if (repairChange) {
      uni.removeStorageSync('repairChange');
    }
  },
  onPullDownRefresh() {
    this.initListDate();
    this.getList().then(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    initListDate(){
      const vm = this;
      vm.orderList = []
      vm.current = 1
      vm.showOrder = false
      vm.hasNextPage = false
    },
    getList(againClick = false) {
      const vm = this;

      uni.showLoading({
        title: '加载中...',
      });
      let param = {
        current: vm.current,
      };
      this.pageAlready = true;
      return new Promise(function (resolve) {
        vm.apiUrl
          .api_func_getrepairorderlist({
            data: {
              ...param,
              openid: vm.memberInfo.openid || '',
            },
          })
          .then((res) => {
            const {
              code,
              data: { list = [] },
            } = res.data;
            if (code == 0 && list.length) {
              // 列表分页
              // if (data.pages == vm.currentPage) {
              //   vm.hasNextPage = true;
              // }
              let checkstatusObj = {
                0: {
                  checkstatusStr: '待受理',
                  className: 'bg61601',
                  colorName: 'color616',
                },
                1: {
                  checkstatusStr: '已受理',
                  className: 'bg00901',
                  colorName: 'theme-color',
                },
                2: {
                  checkstatusStr: '待支付',
                  className: 'bgff001',
                  colorName: 'colorff0',
                },
                3: {
                  checkstatusStr: '维修中',
                  className: 'bgff901',
                  colorName: 'colorff9',
                },
                4: {
                  checkstatusStr: '归还中',
                  className: 'bg61601',
                  colorName: 'color616',
                },
                5: {
                  checkstatusStr: '已签收',
                  className: 'bg36b01',
                  colorName: 'color36b',
                },
                6: {
                  checkstatusStr: '已完成',
                  className: 'bg36b01',
                  colorName: 'color36b'
                },
                7: {
                  checkstatusStr: '已取消',
                  className: 'bg80801',
                  colorName: 'color808',
                },
                8: {
                  checkstatusStr: '已关闭',
                  className: 'bg80801',
                  colorName: 'color808',
                },
              }
              let arr = list.map((item) => {
                if(item){
                  for(let path in checkstatusObj){
                    if(item.checkstatus == path){
                      item.checkstatusStr = checkstatusObj[path].checkstatusStr
                      item.className = checkstatusObj[path].className
                      item.colorName = checkstatusObj[path].colorName

                      // 报修状态未录入快递单号已显示”待受理“——正确用户需在寄出录入快递单号才可以显示”待受理“，
                      // 若只是提交并未录入快递单号，状态应该是”已提交“或”请录入单号“
                      if(item.checkstatus==0 && !item.routercode){
                        item.checkstatusStr = '已提交'
                      }
                      break
                    }else {
                      item.className = checkstatusObj[8].className
                      item.colorName = checkstatusObj[8].colorName
                    }
                  }
                }
                return {
                  ...item,
                  submittime: item.submittime ? vm.dateFormatFun(item.submittime, 'YYYY-MM-DD') : '',
                  serviceTime: item.serviceTime
                    ? vm.dateFormatFun(item.serviceTime, 'YYYY-MM-DD hh:mm')
                    : '',
                };
              });
              vm.orderList = arr;
              // 列表分页
              // vm.orderList = vm.orderList.concat(arr);
              // vm.current++;
            }
          }).finally(() => {
            uni.hideLoading();
            if (againClick) {
              vm.againClick = true;
            }
            if (vm.orderList && vm.orderList.length > 0) {
              vm.showOrder = false;
            } else {
              vm.showOrder = true;
            }
          });

        resolve();
      })
    },
    // 撤回
    api_func_cancelOrder(orderid) {
      const vm = this
      if (!vm.againClick) return;
      vm.againClick = false;
      uni.showLoading({
        title: '加载中...'
      })
      this.apiUrl
        .api_func_cancelOrder({
          data: {
            orderid: orderid,
          },
        })
        .then((res) => {
          uni.hideLoading();
          const { code,msg:message='' } = res.data
          if (code == 0) {
            vm.showMessage({
              title: '撤回报修成功',
              duration: 2000
            })
            vm.sleep(2000).then(()=>{
              vm.initListDate();
              vm.getList();
            })
          }else {
            vm.showMessage({
              title: message,
              icon: 'error',
              duration: 1500
            })
          }
        }).finally(()=>{
          vm.sleep(1500).then(()=>{
            vm.againClick = true;
          })
      })
    },
    // 弹框
    showDrawer(name,order) {
      this.showPop[name] = true;
      if(order){
        this.order = {
          ...order
        }
      }
    },
    closeDrawer(name) {
      this.showPop[name] = false;
    },
    api_func_submitRouterInfo() {
      const vm = this
      // 正则表达式，用于判断字符串是否不包含汉字
      if (vm.containsChinese(vm.order.routercode)) {
        vm.showMessage({
          title: '快递单号不可包含中文',
          duration: 1500,
        });
        return;
      }
      if (!vm.againClick) return;
      vm.againClick = false;
      uni.showLoading({
        title: '加载中...'
      })
      this.apiUrl
        .api_func_submitRouterInfo({
          data: {
            orderid: vm.order.orderid,
            routercode: vm.order.routercode
          },
        })
        .then((res) => {
          uni.hideLoading();
          const { code,msg:message='' } = res.data
          if (code == 0) {
            vm.closeDrawer('expressDelivery')
            vm.showMessage({
              title: '录入快递单号成功',
              duration: 2000
            })
            vm.sleep(2000).then(()=>{
              vm.initListDate();
              vm.getList();
            })
          }else {
            vm.showMessage({
              title: message,
              icon: 'error',
              duration: 1500
            })
          }
        }).finally(()=>{
          vm.sleep(1500).then(()=>{
            vm.againClick = true;
          })
        })
    },
    toLogistics(order){
      const vm = this
      uni.setStorageSync(`order_${order.orderid}`,JSON.stringify(order));
      vm.toPage('/pages/packages/member/logistics/logistics?orderid='+order.orderid,true)
    },
    // 微信支付 start
    // 支付成功
    paySuccess(orderid, againClick = false) {
      const vm = this;
      this.api_func_getrepairorderdetail().then(() => {
        if (vm.order.paystatus == 1) {
          vm.toPage('/pages/order/pay-success/pay-success?orderid='+orderid,true)
          // uni.redirectTo({
          //   url: `/pages/order/pay-success/pay-success?orderid=${orderid}`,
          // });
        } else {
          // if (!againClick) {
          //   this.showPop['confirmResults'] = true;
          // } else {
          //   this.showPop['pendding'] = true;
          // }
        }
      });
    },
    api_func_getrepairorderdetail() {
      const vm = this;
      return new Promise((resolve) => {
        vm.apiUrl
          .api_func_getrepairorderdetail({
            data: {
              orderid: vm.order.orderid,
            },
          })
          .then((res) => {
            const { code, data } = res.data;
            if (code == 0) {
              if (data) {
                vm.order = {
                  ...vm.order,
                  ...data,
                };
                resolve();
              }
            }
          });
      });
    },
    api_func_getpayparams() {
      const vm = this

      if (!vm.againClick) return;
      vm.againClick = false;
      uni.showLoading({
        title: '加载中...'
      })
      this.apiUrl
        .api_func_getpayparams({
          data: {
            orderid: vm.order.orderid,
          },
        })
        .then((res) => {
          uni.hideLoading();
          const { code,msg:message='',data } = res.data
          if (code == 0) {
            // 调起微信支付
            uni.requestPayment({
              provider: 'wxpay', // 支付服务提供商，如 'wxpay'、'alipay'
              // 由支付服务提供商返回的支付信息
              timeStamp: data.timeStamp,
              nonceStr: data.nonceStr,
              package: data.package,
              signType: data.signType,
              paySign: data.paySign,
              success: function (res) {
                console.log('支付成功', res);
                vm.closeDrawer('payment')
                vm.showMessage({
                  title: '支付成功',
                  duration: 2000
                }).then(()=>{
                  uni.setStorageSync('repairChange',true)
                  vm.paySuccess(vm.order.orderid)
                })
              },
              fail: function (err) {
                console.log('支付失败', err);
                const { errMsg="" } = err
                vm.showMessage({
                  title: errMsg || '支付失败',
                  // icon: 'error',
                  duration: 1500
                })
              },
              complete: function () {
                console.log('支付流程完成');
              }
            });

          }else {
            vm.showMessage({
              title: message,
              icon: 'error',
              duration: 1500
            })
          }
        }).finally(()=>{
          vm.sleep(1500).then(()=>{
            vm.againClick = true;
          })
        })
    },
    // 微信支付 end
    // 签收
    signFor(orderid) {
      const vm = this
      if (!vm.againClick) return;
      vm.againClick = false;
      uni.showLoading({
        title: '加载中...'
      })
      this.apiUrl
        .signFor({
          data: {
            orderid: orderid,
          },
        })
        .then((res) => {
          uni.hideLoading();
          const { code,msg:message='' } = res.data
          if (code == 0) {
            vm.showMessage({
              title: '签收成功',
              duration: 2000
            })
            vm.sleep(2000).then(()=>{
              vm.initListDate();
              vm.getList();
            })
          }else {
            vm.showMessage({
              title: message,
              icon: 'error',
              duration: 1500
            })
          }
        }).finally(()=>{
        vm.sleep(1500).then(()=>{
          vm.againClick = true;
        })
      })
    },
    // 快递信息扫码录入
    scanRouterCode() {
      const vm = this;
      // 调用扫码API
      uni.scanCode({
        success: (res) => {
          // 扫码成功回调
          console.log('扫码结果: ' + res.result);
          console.log('条形码类型: ' + res.scanType);
          // 这里可以执行进一步的处理，例如验证序列号等
          // 根据res.result中的内容进行处理
          vm.order = {
            ...vm.order,
            routercode: res.result,
          };
        },
        fail: (err) => {
          // 扫码失败回调
          console.error('扫码失败: ', err);
          const { errMsg } = err;
          if (errMsg) {
            vm.showMessage({
              title: errMsg || 'scanCode API 失效',
              icon: 'error',
              duration: 1500,
            });
          }
        },
      });
    },

  },
};
</script>

<style lang="less" scoped>

</style>
